import requests
import json
from web3 import Web3
import uniswap
from utils.FileUtil import FileUtil

api_key = 'Z6DGTE8ZC1R969PT6P91PBQRHFHXFHCNB9'
#钱包地址或者合约地址
address = '0x0eee1bbb6a0d643211238e1fdf24ce7b3c29a7fe'

#获取以太坊转账记录
def get_transactions(address,startblock=0,endblock=99999999):
    url = f'https://api.etherscan.io/api?module=account&action=txlist&address={address}&startblock={startblock}&endblock={endblock}&sort=asc&apikey={api_key}'
    response = requests.get(url)
    data = json.loads(response.text)
    transactions = data['result']
    return transactions

#根据地址获取abi
def getAbiByAdress(contract_address):
    # define API URL
    api_url = f"https://api.etherscan.io/api?module=contract&action=getabi&address={contract_address}&apikey={api_key}"

    # send HTTP GET request
    response = requests.get(api_url)

    # check status code
    if response.status_code == 200:
        # parse JSON data
        data = response.json()
        # get contract ABI
        abi = data["result"]
        # print contract ABI
        return abi
    else:
        # print error message
        print(f"Error: {response.status_code}")

#根据地址获取合约转移记录
def getTransferByAdress(contract_address):
    # 连接到以太坊节点
    w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/f3fde5c8dc7a42d99214014edbebb793'))

    #获取abi
    contract_abi = getAbiByAdress(contract_address)
    # 创建合约对象
    contract = w3.eth.contract(address=contract_address, abi=contract_abi)

    # 获取最新区块号
    latest_block = w3.eth.block_number

    # 获取过去 10000 个区块中的转移记录
    events = contract.events.Transfer.create_filter(fromBlock=latest_block-10000, toBlock='latest').get_all_entries()
    
    f = FileUtil()
    f.write_file(str(events),"test/"+contract_address+".txt")
    # 遍历转移记录
    for event in events:
        # 获取转移详情
        from_address = event['args']['from']
        to_address = event['args']['to']
        value = event['args']['value']
        print(event)

        # 输出转移详情
        print(f'{from_address} transferred {value} tokens to {to_address}')
        break


# 获取指定代币的交易k线图，接受一个参数：合约地址
def get_candlestick_data(contract_address):
    # 创建一个web3对象，连接到本地节点
    w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/f3fde5c8dc7a42d99214014edbebb793'))
    # 创建一个uniswap对象，传入任意一个账号地址，不需要私钥
    uni = uniswap.Uniswap('0x0000000000000000000000000000000000000000', None, provider='https://mainnet.infura.io/v3/f3fde5c8dc7a42d99214014edbebb793')

    # 获取合约地址对应的代币对象
    token = uni.get_token(contract_address)
    # 获取代币的符号和精度
    token_symbol = token.symbol
    token_decimals = token.decimals

    print(token,uni.get_ex_token_balance(contract_address))
    # 构造一个请求URL，使用uniswap的子图API，查询代币的K线数据
    # 可以根据需要修改时间间隔和数据条数
    # url = f'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2?query={{tokenDayDatas(first: 100, orderBy: date, orderDirection: desc, where: {{token: "{contract_address}"}}) {{date, dailyVolumeToken, dailyVolumeETH, dailyVolumeUSD, totalLiquidityToken, totalLiquidityETH, totalLiquidityUSD, priceUSD}}}}'
    # # 发送请求，获取响应
    # response = requests.get(url)
    # # 检查响应状态码是否为200，表示成功
    # if response.status_code == 200:
    #     if response.headers['Content-Type'] == 'application/json':
    #         data = response.json()
    #     else:
    #         print('Not a JSON response')
    #         f = FileUtil()
    #         f.write_file(response.text.encode('utf-8'),"test1/"+contract_address+".txt")
    #         return
    #     # 从JSON中提取K线数据列表
    #     candlestick_data = data['data']['tokenDayDatas']
    #     # 打印代币符号和K线数据条数
    #     print(f'Candlestick data for {token_symbol}: {len(candlestick_data)} records')
    #     # 返回K线数据列表
    #     return candlestick_data
    # else:
    #     # 如果响应状态码不为200，表示失败，打印错误信息
    #     print(f'Failed to get candlestick data for {token_symbol}: {response.status_code}')
    #     # 返回空列表
    #     return []





